package com.nagat.http;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.InetSocketAddress;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;
import com.sun.net.httpserver.spi.HttpServerProvider;


public class Server {

//	
	public static void main(String[] args) throws Exception{
		
		HttpServerProvider provider = HttpServerProvider.provider();
		
		InetSocketAddress address = new InetSocketAddress(8080);
		
		HttpServer httpServer = provider.createHttpServer(address, 1);
		httpServer.createContext("/login", new HttpHandler() {

			@Override
			public void handle(HttpExchange he) throws IOException {
				
				
				InputStream is = he.getRequestBody();
				
				Headers headers = he.getRequestHeaders();
				
				
				System.out.println(headers.get("username"));;
				
				BufferedReader br = new BufferedReader(new InputStreamReader(is));
				
				StringBuffer sb = new StringBuffer();
				
				String ret = "";
//				System.out.println(br.readLine());
				while ((ret = br.readLine()) != null){
					System.out.println(ret);
					sb.append(ret);
				}
				
				System.out.println(sb);
				he.sendResponseHeaders(200, "ok".length());
				OutputStream os = he.getResponseBody();
				os.write("ok".getBytes());
			}
			
		});
		
		
		httpServer.setExecutor(null);
		httpServer.start();
		
	}
}
